# coding=utf-8

import requests
import re
import time
import random
from peewee import *


db = MySQLDatabase("qq", host="127.0.0.1", user="root", passwd="123456")


class BaseModel(Model):
    class Meta:
        database = db


class Msg(BaseModel):
    content = CharField()
    group = IntegerField()

db.connect()

URLS = {"index": "http://w.qq.com/login.html",
        "qr_code_url": "https://ssl.ptlogin2.qq.com/ptqrshow?appid=%s&e=0&l=L&s=8&d=72&v=4",
        "ptqrlogin": "https://ssl.ptlogin2.qq.com/ptqrlogin?webqq_type=10&remember_uin=1&login2qq=1&aid=%s&u1=http%%3A%%2F%%2Fw.qq.com%%2Fproxy.html%%3Flogin2qq%%3D1%%26webqq_type%%3D10&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=0-0-%s&mibao_css=%s&t=undefined&g=1&js_type=0&js_ver=%s&login_sig=%s",
        "login2": "http://d.web2.qq.com/channel/login2",
        "poll2": "http://d.web2.qq.com/channel/poll2"}

RGEEXS = {"login_url": '\.src\ =\ "(.+?)"',

          "appid": 'g_appid=encodeURIComponent\(\"(\d+)\"\)',
          "sign": 'g_login_sig=encodeURIComponent\(\"(.*?)\"\)',
          "js_ver": 'g_pt_version=encodeURIComponent\(\"(\d+)\"\)',
          "mi_bao_css": 'g_mibao_css=encodeURIComponent\(\"(.*?)\"\)'}


sess = requests.Session()


def main():
    client_id = int(random.uniform(111111, 888888))
    psession_id = ''
    referer = 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2'

    r = sess.get(URLS["index"])
    res = re.search(RGEEXS["login_url"], r.text)
    login_url = res.group(1)

    r = sess.get(login_url)
    res = re.search(RGEEXS["appid"], r.text)
    appid = res.group(1)

    res = re.search(RGEEXS["sign"], r.text)
    sign = res.group(1)

    res = re.search(RGEEXS["js_ver"], r.text)
    js_ver = res.group(1)

    res = re.search(RGEEXS["mi_bao_css"], r.text)
    mi_bao_css = res.group(1)

    get_qr_time = int(time.time())
    r = sess.get(URLS["qr_code_url"] % appid)
    r.encoding = "binary"
    f = open("./static/qr.png", "w+")
    f.write(r.content)
    f.close()

    while True:
        time.sleep(2)

        time_delta = int(time.time()) - get_qr_time
        r = sess.get(URLS["ptqrlogin"] % (appid, time_delta, mi_bao_css, js_ver, sign))
        ret = r.text.split("'")

        if ret[1] == "66":
            print "等待验证"

        elif ret[1] == "0":
            print "登录成功"
            r = sess.get(ret[5])

            while True:
                data = ({"r": '{"ptwebqq":"%s","clientid":%s,"psessionid":"%s","status":"online"}'
                        % (sess.cookies["ptwebqq"], client_id, psession_id)})
                headers = {"referer": referer}
                r = sess.post(URLS["login2"], data=data, headers=headers)
                ret = r.json()

                if ret['retcode'] != 0:
                    break

                vfwebqq = ret['result']['vfwebqq']
                psession_id = ret['result']['psessionid']
                msgId = int(random.uniform(20000, 50000))

                while True:
                    time.sleep(2)
                    print data
                    data = ({"r": '{"ptwebqq":"%s","clientid":"%s","psessionid":"%s","key":""}'
                            % (sess.cookies["ptwebqq"], client_id, psession_id)})
                    headers = {"referer": referer}
                    r = sess.post(URLS["poll2"], data=data, headers=headers)
                    if r.text == "":
                        break

                    ret = r.json()
                    print ret
                    if ret['retcode'] == 116:
                        sess.cookies["ptwebqq"] = ret['p']
                        continue
                    elif ret['retcode'] == 0:
                        for msg in ret['result']:
                            msg_type = msg['poll_type']
                            if msg_type == 'group_message':
                                txt = msg['value']['content'][1]
                                msg = Msg(content=txt, group=msg['value']['info_seq'])
                                msg.save()

        elif ret[1] == "65":
            print "qrcode 失效"

        elif ret[1] == "67":
            print "验证中"

        else:
            print "未知错误"

if __name__ == "__main__":
    main()
